Imports System.IO
Imports System.Web
Imports Cdm.AppServices.Log

Partial Class admin_appUploadFormsReports
    Inherits System.Web.UI.Page
    Const C_TABLE_NAMESPACE As String = "Cdm.DataCore.CaseNotes."
    Const _CLASS_NAME As String = "admin_appUploadFormsReports"
    Private sMessage As String

    Protected Enum FileType As Integer
        Form = 0
        Report = 1
    End Enum

    Protected Sub Page_Load(ByVal sender As Object, _
                            ByVal e As System.EventArgs) _
                            Handles Me.Load

        SetupJavaScript()
        If Not Page.IsPostBack Then
            Me.FormsScrollingGridView.Sort("FormShortName", SortDirection.Ascending)
        End If

        Dim sType As String
        Dim sDataKey(0) As String
        sDataKey(0) = "Id"

        Me.FileTypeDropDownList.Attributes.Add("onchange", "document.getElementById(""mainSection"").style.visibility=""hidden""; document.getElementById(""saveSection"").style.visibility=""hidden"";")
        If Me.FileTypeDropDownList.SelectedValue.Equals("") Then
            sType = C_TABLE_NAMESPACE & "Forms"
            Me.FormsObjectDataSource.TypeName = sType
            Me.FormsObjectDataSource.DataObjectTypeName = sType
        End If
        sType = C_TABLE_NAMESPACE & Me.FileTypeDropDownList.SelectedValue
        Me.FormsScrollingGridView.DataKeyNames = sDataKey
        Me.ReportsScrollingGridView.DataKeyNames = sDataKey
        If Me.IsPostBack Then
            Me.FormsObjectDataSource.DataObjectTypeName = sType
            Me.NewFormsObjectDataSource.DataObjectTypeName = sType
            Me.NewFormsObjectDataSource.TypeName = sType
            Me.FormsObjectDataSource.TypeName = sType
        End If


    End Sub

    Protected Sub FileTypeDropDownList_SelectedIndexChanged(ByVal sender As Object, _
                                                            ByVal e As System.EventArgs) _
                                                            Handles FileTypeDropDownList.SelectedIndexChanged

        If Me.NewRecordPanel.Visible Then

            Me.NewRecordPanel.Visible = False
            Me.SaveButton.Visible = False
            Me.CancelButton.Visible = False

            If Me.FileTypeDropDownList.SelectedValue = "Forms" Then
                ShowGridViews(True, False)
            Else
                ShowGridViews(False, True)
            End If

            Me.AddButton.Visible = True
            Me.FileExistsLabel.Visible = False
            Me.shortName.Text = ""

        Else

            Dim commandField As CommandField = Nothing

            Me.FormsObjectDataSource.TypeName = C_TABLE_NAMESPACE & Me.FileTypeDropDownList.SelectedValue
            Me.NewFormsObjectDataSource.TypeName = C_TABLE_NAMESPACE & Me.FileTypeDropDownList.SelectedValue
            Me.FormsObjectDataSource.DataObjectTypeName = C_TABLE_NAMESPACE & Me.FileTypeDropDownList.SelectedValue
            Me.NewFormsObjectDataSource.DataObjectTypeName = C_TABLE_NAMESPACE & Me.FileTypeDropDownList.SelectedValue
            Me.NewFormsObjectDataSource.Select()
            Me.FormsObjectDataSource.Select()

            ' For deleting all columns and adding new ones depending on the Type
            'Me.grdForms.Columns.Clear()
            If (Me.FileTypeDropDownList.SelectedValue = "Forms") Then

                ShowGridViews(True, False)

                Me.FormsScrollingGridView.DataBind()
            Else

                ShowGridViews(False, True)
                Me.ReportsScrollingGridView.DataBind()
            End If

        End If

    End Sub

    Private Sub ShowGridViews(ByVal isFormGridVisible As Boolean, ByVal isReportGridVisible As Boolean)

        Me.FormsScrollingGridView.Visible = isFormGridVisible
        Me.DeleteMultiFormButton.Visible = isFormGridVisible
        Me.DeleteFormTableRow.Visible = isFormGridVisible

        Me.ReportsScrollingGridView.Visible = isReportGridVisible
        Me.DeleteMultiReportButton.Visible = isReportGridVisible
        Me.DeleteReportTableRow.Visible = isReportGridVisible
    End Sub

    Protected Sub AddColumnsToGridView(ByVal dataField As String, ByVal headerText As String)
        Dim boundField As BoundField
        boundField = New BoundField()
        boundField.DataField = dataField
        boundField.HeaderText = headerText
        Me.FormsScrollingGridView.Columns.Add(boundField)
    End Sub
    Protected Sub FormsObjectDataSource_DataBinding(ByVal sender As Object, _
                                           ByVal e As System.EventArgs) _
                                           Handles FormsObjectDataSource.DataBinding
        CheckMatch("FormsObjectDataSource_DataBinding")
    End Sub

    Protected Sub FormsObjectDataSource_ObjectCreating(ByVal sender As Object, _
                                              ByVal e As System.Web.UI.WebControls.ObjectDataSourceEventArgs) _
                                              Handles FormsObjectDataSource.ObjectCreating
        CheckMatch("FormsObjectDataSource_ObjectCreating")
    End Sub

    Protected Sub FormsObjectDataSource_Selecting(ByVal sender As Object, _
                                         ByVal e As System.Web.UI.WebControls.ObjectDataSourceSelectingEventArgs) _
                                         Handles FormsObjectDataSource.Selecting
        CheckMatch("FormsObjectDataSource_Selecting")
        Me.FormsObjectDataSource.TypeName = C_TABLE_NAMESPACE & Me.FileTypeDropDownList.SelectedValue
        Me.FormsObjectDataSource.DataObjectTypeName = C_TABLE_NAMESPACE & Me.FileTypeDropDownList.SelectedValue
    End Sub

    Protected Sub FormsObjectDataSource_Updating(ByVal sender As Object, _
                                        ByVal e As System.Web.UI.WebControls.ObjectDataSourceMethodEventArgs) _
                                        Handles FormsObjectDataSource.Updating
        CheckMatch("FormsObjectDataSource_Updating")
    End Sub



    Private Sub CheckMatch(ByVal sproc As String)

        Dim sDataSourceTN As String
        Dim sDataSourceDOTN As String
        Dim sDropDownVal As String
        sMessage = ""
        sDataSourceTN = Me.FormsObjectDataSource.TypeName
        sDataSourceDOTN = Me.FormsObjectDataSource.DataObjectTypeName
        sDropDownVal = Me.FileTypeDropDownList.SelectedValue
        If Not (sDataSourceDOTN.Equals(sDropDownVal)) Then
            sMessage = "Object is " & sDataSourceDOTN & "; dropdown is " & sDropDownVal
        End If
        If Not (sDataSourceDOTN.Equals(sDataSourceTN)) Then
            sMessage = sMessage & "    " & "Object is " & sDataSourceDOTN & "; typename is " & sDataSourceTN
        End If
        If Not (sDataSourceDOTN.Equals(sDataSourceTN)) Then
            sMessage = sMessage & "    " & "Object is " & sDataSourceDOTN & "; typename is " & sDataSourceTN
        End If
        If Not (sMessage.Equals("")) Then
            sMessage = sMessage & " ! from " & sproc
        End If

    End Sub

    Protected Sub AddButton_Click(ByVal sender As Object, _
                                  ByVal e As System.EventArgs) _
                                  Handles AddButton.Click

        ShowGridViews(False, False)
        ' Me.SubTitleLabel.Visible = False
        Me.AddButton.Visible = False
        
        Me.NewRecordPanel.Visible = True
        Me.SaveButton.Visible = True
        Me.CancelButton.Visible = True

    End Sub

    Protected Sub SaveButton_Click(ByVal sender As Object, _
                                   ByVal e As System.EventArgs) _
                                   Handles SaveButton.Click

        Dim filePath As String
        ' Root path to where files/reports are uploaded on the server.
        filePath = Me.MapPath(Me.Request.ApplicationPath)
        Dim file As FileInfo

        ' Determine if we're dealing with forms or reports.
        If (Me.FileTypeDropDownList.SelectedValue = "Forms") Then

            ' Check to see if the file already exists on the server.
            file = New FileInfo(filePath & "\Forms\" & Me.FileUpload1.FileName)
            If Not file.Exists Then

                ' Upload the file to the server.
                Dim form As Cdm.DataCore.CaseNotes.Forms
                form = New Cdm.DataCore.CaseNotes.Forms()
                form.FormShortName = Me.shortName.Text
                form.FormLongName = Me.description.Text
                form.FormFileName = Me.FileUpload1.FileName
                form.DateUploaded = Now()
                form.Persist()

                filePath = filePath & "\Forms\"
                FileUpload1.SaveAs(filePath & Me.FileUpload1.FileName)

                Me.NewRecordPanel.Visible = False
                Me.SaveButton.Visible = False
                Me.CancelButton.Visible = False

                SetStatus("Upload successful. To grant permissions for users to see this file visit 'Edit Role Configuration'.")
                ShowGridViews(True, False)
                Me.AddButton.Visible = True
                Me.shortName.Text = ""
                Me.description.Text = ""
                Me.FileExistsLabel.Visible = False

                ' Rebind the grid.
                Me.FormsScrollingGridView.DataBind()
                SetStatus("Form has been added.")
            Else

                Me.FileExistsLabel.Visible = True

            End If

        Else

            ' Check to see if the file already exists on the server.
            file = New FileInfo(filePath & "\Reports\" & Me.FileUpload1.FileName)
            If Not file.Exists Then

                ' Upload the file to the server.
                Dim report As Cdm.DataCore.CaseNotes.Reports
                report = New Cdm.DataCore.CaseNotes.Reports()
                report.ReportShortName = Me.shortName.Text
                report.ReportLongName = Me.description.Text
                report.ReportFileName = Me.FileUpload1.FileName
                report.DateUploaded = Now()
                report.Persist()

                filePath = filePath & "\Reports\"
                FileUpload1.SaveAs(filePath & Me.FileUpload1.FileName)

                Me.NewRecordPanel.Visible = False
                Me.SaveButton.Visible = False
                Me.CancelButton.Visible = False

                SetStatus("Upload successful. To grant permissions for users to see this file visit 'Edit Role Configuration'.")
                ShowGridViews(False, True)
                Me.AddButton.Visible = True
                Me.shortName.Text = ""
                Me.description.Text = ""
                Me.FileExistsLabel.Visible = False

                ' Rebind the grid.
                Me.ReportsScrollingGridView.DataBind()
                SetStatus("Report has been added.")
            Else

                Me.FileExistsLabel.Visible = True

            End If

        End If

    End Sub

    Protected Sub CancelButton_Click(ByVal sender As Object, _
                                     ByVal e As System.EventArgs) _
                                     Handles CancelButton.Click

        Me.NewRecordPanel.Visible = False
        Me.SaveButton.Visible = False
        Me.CancelButton.Visible = False

        If Me.FileTypeDropDownList.SelectedValue = "Forms" Then
            ShowGridViews(True, False)
        Else
            ShowGridViews(False, True)
        End If

        Me.AddButton.Visible = True
        Me.FileExistsLabel.Visible = False
        Me.shortName.Text = ""
        SetStatus("Action has been cancelled.")

    End Sub

    Protected Sub DeleteForms()

        Dim file As FileInfo
        ' Root path of files.
        Dim rootPath As String = Me.MapPath(Me.Request.ApplicationPath)
        Dim gridRow As GridViewRow

        ' Determine what view we're in, whether it's Forms view or Reports view.
        If Me.FormsScrollingGridView.Visible Then

            For Each gridRow In Me.FormsScrollingGridView.Rows

                ' Determine if the form is marked for deletion.
                If CType(gridRow.Cells(0).Controls(1), CheckBox).Checked Then

                    Dim formId As Integer = CInt(Me.FormsScrollingGridView.DataKeys(gridRow.RowIndex).Values(0))
                    Dim deleteForm As Cdm.DataCore.CaseNotes.Forms = Cdm.DataCore.CaseNotes.Forms.Retrieve(formId)

                    ' Determine if the form exists physically on the server.
                    If Me.FileExists(rootPath, deleteForm.FormFileName, FileType.Form) Then

                        ' Get a reference to the file and delete it.
                        file = New FileInfo(rootPath & "\Forms\" & deleteForm.FormFileName)
                        file.Delete()

                    End If

                    ' Delete the form reference in the database.
                    Cdm.DataCore.CaseNotes.Forms.Retrieve(CInt(Me.FormsScrollingGridView.DataKeys(gridRow.RowIndex).Values(0))).Remove()

                End If

            Next

            Me.FormsScrollingGridView.DataBind()

        ElseIf Me.ReportsScrollingGridView.Visible Then

            For Each gridRow In Me.ReportsScrollingGridView.Rows
                Dim reportId As Integer = CInt(Me.ReportsScrollingGridView.DataKeys(gridRow.RowIndex).Values(0))
                Dim deleteReport As Cdm.DataCore.CaseNotes.Reports = Cdm.DataCore.CaseNotes.Reports.Retrieve(reportId)

                ' Determine if the report is marked for deletion.
                If CType(gridRow.Cells(0).Controls(1), CheckBox).Checked Then

                    ' Determine if the report exists physically on the server.
                    If Me.FileExists(rootPath, deleteReport.ReportFileName, FileType.Report) Then

                        ' Get a reference to the file and delete it.
                        file = New FileInfo(rootPath & "\Reports\" & deleteReport.ReportFileName)
                        file.Delete()

                    End If

                    ' Delete the report reference in the database.
                    deleteReport.Remove()

                End If

            Next

            Me.ReportsScrollingGridView.DataBind()

        End If

    End Sub

    Protected Function FileExists(ByVal rootPath As String, _
                                  ByVal fileName As String, _
                                  ByVal fileType As FileType) As Boolean

        ' Determine if the file being deleted exists physically on the server.
        Dim file As FileInfo
        Select Case fileType

            Case admin_appUploadFormsReports.FileType.Form

                file = New FileInfo(rootPath & "\Forms\" & fileName)
                Return file.Exists

            Case admin_appUploadFormsReports.FileType.Report

                file = New FileInfo(rootPath & "\Reports\" & fileName)
                Return file.Exists

        End Select

        Return False

    End Function

    Protected Sub FormsScrollingGridView_RowCancelingEdit(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCancelEditEventArgs) Handles FormsScrollingGridView.RowCancelingEdit
        SetStatus("Update Cancelled.")
    End Sub

    Protected Sub FormsScrollingGridView_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles FormsScrollingGridView.RowCommand

        Try

            If e.CommandArgument = "DeleteMulti" Then
                Me.DeleteForms()
                Me.FormsObjectDataSource.TypeName = C_TABLE_NAMESPACE & Me.FileTypeDropDownList.SelectedValue
                Me.FormsObjectDataSource.DataObjectTypeName = C_TABLE_NAMESPACE & Me.FileTypeDropDownList.SelectedValue
                SetStatus("Form(s) have been deleted.")
            End If


        Catch ex As Exception
            SetStatus("Error in Deleting Forms - " + ex.Message)
            ErrorLog(_CLASS_NAME, "An error occurred in the grdForms_RowCommand() method while deleting forms.", ex)
        End Try
    End Sub

    Protected Sub FormsScrollingGridView_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles FormsScrollingGridView.RowDataBound
        If e.Row.DataItemIndex = 0 Then
            AccessibilityController.AddImageToSortableGridHeaders(FormsScrollingGridView)
        End If
        AccessibilityController.SetGridViewEditToolTips(e.Row, Me.FormsScrollingGridView)

        Dim txtFormShortName As TextBox = CType(e.Row.FindControl("txtFormShortName"), TextBox)
        If Not txtFormShortName Is Nothing Then
            SetFocus(txtFormShortName.ClientID)
        End If
    End Sub

    Protected Sub FormsScrollingGridView_RowUpdated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdatedEventArgs) Handles FormsScrollingGridView.RowUpdated
        SetStatus("Form Updated.")
    End Sub

    Protected Sub FormsScrollingGridView_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles FormsScrollingGridView.RowUpdating
        CheckMatch("grdForms_RowUpdating")
    End Sub

    Protected Sub ReportsScrollingGridView_RowCancelingEdit(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCancelEditEventArgs) Handles ReportsScrollingGridView.RowCancelingEdit
        SetStatus("Update Cancelled.")
    End Sub

    Protected Sub ReportsScrollingGridView_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles ReportsScrollingGridView.RowCommand
        Try

            If e.CommandArgument = "DeleteMulti" Then

                Me.DeleteForms()
                Me.FormsObjectDataSource.TypeName = C_TABLE_NAMESPACE & Me.FileTypeDropDownList.SelectedValue
                Me.FormsObjectDataSource.DataObjectTypeName = C_TABLE_NAMESPACE & Me.FileTypeDropDownList.SelectedValue
                SetStatus("Report(s) have been deleted.")
            End If


        Catch ex As Exception
            ErrorLog(_CLASS_NAME, "An error occurred in the grdForms_RowCommand() method while deleting reports.", ex)
            SetStatus("Error Deleting Reports - " + ex.Message)
        End Try
    End Sub

    Protected Sub ReportsScrollingGridView_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles ReportsScrollingGridView.RowDataBound
        If e.Row.DataItemIndex = 0 Then
            AccessibilityController.AddImageToSortableGridHeaders(ReportsScrollingGridView)
        End If
        AccessibilityController.SetGridViewEditToolTips(e.Row, Me.ReportsScrollingGridView)
        ' Hide the filename field.

        Dim txtReportShortName As TextBox = CType(e.Row.FindControl("txtReportShortName"), TextBox)
        If Not txtReportShortName Is Nothing Then
            SetFocus(txtReportShortName.ClientID)
        End If
    End Sub

    Protected Sub ReportsScrollingGridView_RowUpdated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdatedEventArgs) Handles ReportsScrollingGridView.RowUpdated
        SetStatus("Update Successful.")
    End Sub

    Protected Sub ReportsScrollingGridView_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles ReportsScrollingGridView.RowUpdating
        CheckMatch("grdReports_RowUpdating")
    End Sub


    Private Sub ClearStatus()
        SetStatus("")
    End Sub
    Private Sub SetStatus(ByVal message As String)
        Dim mymaster As ASP.admin_admin_master = CType(Me.Master, ASP.admin_admin_master)
        mymaster.SetStatus(message)
    End Sub

    Private Sub SetupJavaScript()

        EntityController.JavaScriptAddChildDiv(Me.FormsScrollingGridView.DivClientId, CInt(Me.FormsScrollingGridView.ToolTip))
        ClientScript.RegisterStartupScript(Me.GetType(), "scrollDivs", EntityController.JavaScriptScrollingGridStartup(Me.FormsScrollingGridView), True)

        EntityController.JavaScriptAddChildDiv(Me.ReportsScrollingGridView.DivClientId, CInt(Me.ReportsScrollingGridView.ToolTip))
        ClientScript.RegisterStartupScript(Me.GetType(), "scrollDivs2", EntityController.JavaScriptScrollingGridStartup(Me.ReportsScrollingGridView), True)


        EntityController.JavaScriptSetFixedHeight(28)
    End Sub

    Protected Sub DeleteMultiReportButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles DeleteMultiReportButton.Click

        Me.DeleteForms()
        Me.FormsObjectDataSource.TypeName = C_TABLE_NAMESPACE & Me.FileTypeDropDownList.SelectedValue
        Me.FormsObjectDataSource.DataObjectTypeName = C_TABLE_NAMESPACE & Me.FileTypeDropDownList.SelectedValue
        SetStatus("Report(s) have been deleted.")
    End Sub

    Protected Sub DeleteMultiFormButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles DeleteMultiFormButton.Click
        Me.DeleteForms()
        Me.FormsObjectDataSource.TypeName = C_TABLE_NAMESPACE & Me.FileTypeDropDownList.SelectedValue
        Me.FormsObjectDataSource.DataObjectTypeName = C_TABLE_NAMESPACE & Me.FileTypeDropDownList.SelectedValue
        SetStatus("Form(s) have been deleted.")
    End Sub
End Class
